import { Input, Button } from 'antd'
import { cloneDeep } from 'lodash'
import style from './style.module.scss'

const List = (props) => {
  const { children = [], changeChildren } = props

  const addItemToChildren = () => {
    const newChildren = [...children]
    newChildren.push({
      name: 'Item',
      attributes: {
        title: '',
        description: '',
        imageUrl: '',
        link: ''
      },
      children: []
    })
    changeChildren(newChildren)
  }
  const deleteItemFromChildren = (index) => {
    const newChildren = [...children]
    newChildren.splice(index, 1)
    changeChildren(newChildren)
  }

  const changeChildrenItem = (index, key, value) => {
    const originItem = children[index]
    const item = cloneDeep(originItem)
    item.attributes[key] = value

    const newChildren = [...children]
    newChildren.splice(index, 1, item)
    changeChildren(newChildren)
  }

  return (
    <div className={style.wrapper}>
      <Button
        type="primary"
        className={style.button}
        onClick={addItemToChildren}
      >
        新增列表项
      </Button>
      {children.map(({ attributes }, index) => (
        <div className={style.area} key={index}>
          <div
            className={style.delete}
            onClick={() => deleteItemFromChildren(index)}
          >
            X
          </div>
          <div className={style.row}>
            <span className={style.label}>标题</span>
            <Input
              value={attributes.title}
              onChange={(e) =>
                changeChildrenItem(index, 'title', e.target.value)
              }
              className={style.content}
              placeholder="请输入标题"
            />
          </div>
          <div className={style.row}>
            <span className={style.label}>描述</span>
            <Input
              value={attributes.description}
              onChange={(e) =>
                changeChildrenItem(index, 'description', e.target.value)
              }
              className={style.content}
              placeholder="请输入描述"
            />
          </div>
          <div className={style.row}>
            <span className={style.label}>图片</span>
            <Input
              value={attributes.imageUrl}
              onChange={(e) =>
                changeChildrenItem(index, 'imageUrl', e.target.value)
              }
              className={style.content}
              placeholder="请输入图片地址"
            />
          </div>
          <div className={style.row}>
            <span className={style.label}>链接</span>
            <Input
              value={attributes.link}
              onChange={(e) =>
                changeChildrenItem(index, 'link', e.target.value)
              }
              className={style.content}
              placeholder="请输入跳转链接"
            />
          </div>
        </div>
      ))}
    </div>
  )
}

export default List
